package com.zzw.springboot.controller;


import com.zzw.springboot.bean.Purchase;
import com.zzw.springboot.bean.PurchaseItem;
import com.zzw.springboot.service.PurchaseService;
import com.zzw.springboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 采购单控制器
 */
@RestController
@RequestMapping("/purchase")
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;

    /**
     * 创建采购单
     */
    @PostMapping("/add")
    public Result add(@RequestBody @Valid Purchase purchase, HttpSession session) {
        // 设置创建人ID
        Object userId = session.getAttribute("userId");
        if (userId != null) {
            purchase.setCreatorId((Integer) userId);
        }

        int result = purchaseService.addPurchase(purchase);
        if (result > 0) {
            return Result.success("创建采购单成功");
        } else {
            return Result.error("创建采购单失败");
        }
    }

    /**
     * 更新采购单
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Valid Purchase purchase) {
        int result = purchaseService.updatePurchase(purchase);
        if (result > 0) {
            return Result.success("更新采购单成功");
        } else {
            return Result.error("更新失败，只有草稿状态的采购单才能修改");
        }
    }

    /**
     * 删除采购单
     */
    @DeleteMapping("/delete/{purchaseId}")
    public Result delete(@PathVariable Integer purchaseId) {
        int result = purchaseService.deletePurchase(purchaseId);
        if (result > 0) {
            return Result.success("删除采购单成功");
        } else {
            return Result.error("删除失败，只有草稿状态的采购单才能删除");
        }
    }

    /**
     * 批量删除采购单
     */
    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestBody Integer[] purchaseIds) {
        int result = purchaseService.deletePurchaseBatch(purchaseIds);
        if (result > 0) {
            return Result.success("批量删除采购单成功");
        } else {
            return Result.error("批量删除采购单失败");
        }
    }

    /**
     * 获取采购单详情
     */
    @GetMapping("/detail/{purchaseId}")
    public Result detail(@PathVariable Integer purchaseId) {
        Purchase purchase = purchaseService.getPurchaseById(purchaseId);
        if (purchase != null) {
            return Result.success().add("data", purchase);
        } else {
            return Result.error("采购单不存在");
        }
    }

    /**
     * 提交审核
     */
    @PutMapping("/submit/{purchaseId}")
    public Result submit(@PathVariable Integer purchaseId) {
        // 更新状态为审核中(1)
        int result = purchaseService.approvePurchase(purchaseId, null, 1);
        if (result > 0) {
            return Result.success("提交审核成功");
        } else {
            return Result.error("提交审核失败");
        }
    }

    /**
     * 审批采购单
     */
    @PutMapping("/approve")
    public Result approve(@RequestBody Map<String, Object> params, HttpSession session) {
        Integer purchaseId = (Integer) params.get("purchaseId");
        Integer status = (Integer) params.get("status");

        // 获取当前用户ID
        Object userId = session.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或会话已过期");
        }

        int result = purchaseService.approvePurchase(purchaseId, (Integer) userId, status);
        if (result > 0) {
            return Result.success("审批操作成功");
        } else {
            return Result.error("审批失败，只有审核中状态的采购单才能审批");
        }
    }

    /**
     * 取消采购单
     */
    @PutMapping("/cancel/{purchaseId}")
    public Result cancel(@PathVariable Integer purchaseId) {
        int result = purchaseService.cancelPurchase(purchaseId);
        if (result > 0) {
            return Result.success("取消采购单成功");
        } else {
            return Result.error("取消失败，已入库和已完成的采购单不能取消");
        }
    }

    /**
     * 入库处理
     */
    @PutMapping("/receive")
    public Result receive(@RequestBody Map<String, Object> params, HttpSession session) {
        Integer purchaseId = (Integer) params.get("purchaseId");
        @SuppressWarnings("unchecked")
        List<PurchaseItem> items = (List<PurchaseItem>) params.get("items");

        // 获取当前用户ID
        Object userId = session.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或会话已过期");
        }

        int result = purchaseService.receiveItems(purchaseId, (Integer) userId, items);
        if (result > 0) {
            return Result.success("入库处理成功");
        } else {
            return Result.error("入库处理失败，只有已审核状态的采购单才能入库");
        }
    }

    /**
     * 查询采购单列表
     */
    @GetMapping("/list")
    public Result list(Purchase purchase) {
        List<Purchase> list = purchaseService.getPurchaseList(purchase);
        return Result.success().add("data", list).add("total", list.size());
    }

    /**
     * 获取采购单明细
     */
    @GetMapping("/items/{purchaseId}")
    public Result getItems(@PathVariable Integer purchaseId) {
        List<PurchaseItem> items = purchaseService.getPurchaseItemsByPurchaseId(purchaseId);
        return Result.success().add("data", items);
    }

    /**
     * 生成采购单号
     */
    @GetMapping("/generateNo")
    public Result generatePurchaseNo() {
        String purchaseNo = purchaseService.generatePurchaseNo();
        return Result.success().add("data", purchaseNo);
    }
}
